import json
import os
import shutil
import time

config = {}
logt = time.time()

def log(text):
    localtime = time.asctime(time.localtime(time.time()))
    with open("log" + str(logt) + ".txt", 'a') as file_object:
        s="["+localtime+"] "+text+"\n"
        print(s)
        file_object.write(s)


def copyFile(source, target):
    try:
        shutil.copyfile(source, target)
        log("Success: %s" % source)
    except IOError as e:
        log("Error: Unable to copy file. %s" % e)
    except:
        log("Error: Unknown Error while copying %s" % source)


def strContain(source, targets):
    for target in targets:
        if target in source:
            return True
    return False


def main():
    log("Start...")

    try:
        with open("config.json") as config_json:
            config = json.load(config_json)
    except:
        log("Error: config.json Not Found!")
        log("Exit...")
        exit()

    if not os.path.isdir(config['target']):
        os.mkdir(os.path.join(os.getcwd(), config['target']))
    for p in config['path']:
        if os.path.isdir(p):
            for root, dirs, files in os.walk(p):
                if not root == os.path.join(os.getcwd(), config['target']):
                    for f in files:
                        if strContain(f, config['symbols']):
                            copyFile(os.path.join(root, f), os.path.join(
                                os.getcwd(), os.path.join(config['target'], f)))
        else:
            log("Error: %s not a folder or driver." % p)

    log("Done...")


main()
